//
//  ViewController.m
//  MateNet
//
//  Created by ky on 12-11-18.
//  Copyright (c) 2012年 ky. All rights reserved.
//

#import "LoginViewController.h"

static NSString* m_strToken;

static NSString* m_strUid;

@implementation LoginViewController

+(NSString*)GetToken
{
    return m_strToken;
}

+(NSString*)GetUid
{
    return m_strUid;
}

@synthesize m_loginWeb;

-(NSURLRequest*) GetLoginRequest
{
    NSString* url = @"https://api.weibo.com/oauth2/authorize?client_id=2251639560&redirect_uri=http://weibo.com&display=mobile&response_type=token";
    
    NSURL* weibo = [NSURL URLWithString: url];
    
    NSURLRequest* request = [NSURLRequest requestWithURL: weibo];
    
    return request;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    NSURLRequest* request = [self GetLoginRequest];
    
    NSLog(@"%@", request.URL.absoluteString);
    
    [m_loginWeb loadRequest:request];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)StoreToken:(NSString*) strToken
{
    NSArray* array = [strToken componentsSeparatedByString:@"&"];
    
    for (int i = 0; i < [array count]; ++i)
    {
        NSString* str = [array objectAtIndex:i];
        
        if ([str hasPrefix:@"access_token"] == YES)
        {
            NSArray* tempArray = [str componentsSeparatedByString:@"="];
            
            if ([tempArray count] > 1)
            {
                m_strToken = [tempArray objectAtIndex:1];
            }
        }
        
        if ([str hasPrefix:@"uid"] == YES) 
        {
            NSArray* tempArray = [str componentsSeparatedByString:@"="];
            
            if ([tempArray count] > 1)
            {
                m_strUid = [tempArray objectAtIndex:1];
            }
        }
    }
}

-(BOOL)LoginToWeibo:(NSURLRequest*)request
{
    NSString* strUrl = request.URL.absoluteString;
    
    NSLog(@"%@", strUrl);
    
    NSArray* array = [strUrl componentsSeparatedByString:@"#"];
    
    if ([array count] > 1)
    {
        [self StoreToken: [array objectAtIndex:1]];
        
        return YES;
    }
    
    return NO;
}

-(void)ShowWeiboFrame
{
    [self performSegueWithIdentifier:@"show" sender:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"%@", request.URL.absoluteString);
    
    if ([self LoginToWeibo: request] == YES)
    {
        [self ShowWeiboFrame];
    }
    
    return YES;
}

@end
